//
//  FactoryMessageViewController.m
//  MagictoHire
//
//  Created by huayu01 on 2017/12/4.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "FactoryMessageViewController.h"
#import "FactoryMessageTableViewCell.h"
#import "TZImagePickerController.h"
#import "CloseAreaViewController.h"
#import <AVKit/AVKit.h>
#import <Photos/PHPhotoLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "FactoryIntroductionViewController.h"
#import "KSPhotoBrowser.h"
#import "FactoryTypeViewController.h"
#import "FactoryMessageModel.h"
#import "FactoryImgsModel.h"
#import "FactoryProductModel.h"
#import "UserModel.h"
#import "FactoryCategoryModel.h"
#import "FactoryMapViewController.h"

//自定义的枚举
typedef NS_ENUM(NSInteger, ChosePhontType) {
    ChosePhontTypeAlbum,  //相册
    ChosePhontTypeCamera   //相机
};

@interface FactoryMessageViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate, TZImagePickerControllerDelegate, FactoryIntroductionViewControllerDelegate, KSPhotoBrowserDelegate,UITextViewDelegate>
{
    CGFloat scrollViewOffSetY;
    CGFloat remainingDistanceY;
    CGFloat beforeMigrationY;
    NSMutableArray *photoArr;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    UILabel *tipLabel;
}
@property (nonatomic, strong) UITableView *factoryMessageTableView;
@property (nonatomic, strong) NSMutableArray *messageNameArr;
@property (nonatomic, strong) NSMutableArray *detailMessageNameArr;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) UIImageView *userIcon;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, strong) NSMutableArray *imageStringArr;
@property (nonatomic, copy) NSString *addressStr;
@property (nonatomic, strong) UICollectionView *pictureCollectionView;
@property (nonatomic, copy) NSString *productId;
@property (nonatomic, copy) NSString *areaId;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end

@implementation FactoryMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self requestUserMessage];
    [self setupUI];
    [self setupFactoryMessageTableView];
    [self requestFactoryMessage];
    _areaId = @"";
    _productId = @"";
    self.imageStringArr = [NSMutableArray array];
    photoArr = [NSMutableArray array];
    self.imageArr = [NSMutableArray array];
    self.messageNameArr = @[@"公司LOGO", @"工厂名称", @"ID", @"常用地", @"负责人", @"联系电话", @"工厂定位", @"联系地址", @"工厂简介", @"工厂类型(产品)", @""].mutableCopy;
    self.detailMessageNameArr = @[@"", @"", @"", @"", @"", @"", @"", @"", @"", @"", @""].mutableCopy;
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpantanchu:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)setupUI {
    self.navigationItem.rightBarButtonItem.enabled = NO;
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveFactoryMessage)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationItem.title = @"工厂信息";
}

- (void)setupFactoryMessageTableView {
    _factoryMessageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _factoryMessageTableView.delegate = self;
    _factoryMessageTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _factoryMessageTableView.tableHeaderView = view;
    _factoryMessageTableView.tableFooterView = view;
    _factoryMessageTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_factoryMessageTableView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messageNameArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 90 * displaywidth;
    } else if (indexPath.row == _messageNameArr.count-1) {
        CGFloat twelfthCellHeight = 45 * displaywidth;
        if (self.imageArr.count > 0) {
            if (self.imageArr.count > 4) {
                twelfthCellHeight = 51 + (SCREEN_WIDTH - 3 * 5 * 2 - 40) * 2 / 4  + 25;
            } else {
                twelfthCellHeight = 51 + (SCREEN_WIDTH - 3 * 5 * 2 - 40) / 4  + 25;
            }
        } else {
            twelfthCellHeight = 45 * displaywidth;
        }
        
        return twelfthCellHeight;
    } else {
        return 45 * displaywidth;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 10) {
        FactoryMessageTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"FactoryMessageTableViewCell" owner:self options:nil].lastObject;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _pictureCollectionView = cell.pictureCollectionView;
        NSInteger constant = 5;
        NSInteger itemWidth = (SCREEN_WIDTH - 3 * constant * 2 - 40) / 4;
        CGFloat collectionViewHeight;
        if (_imageArr.count > 0) {
            if (_imageArr.count > 4) {
                collectionViewHeight = itemWidth * 2 + 10;
            } else {
                collectionViewHeight = itemWidth + 10;
            }
        } else {
            collectionViewHeight = 5;
        }
        cell.pictureCollectionView.delegate = self;
        cell.pictureCollectionView.dataSource = self;
        cell.pictureCollectionView.frame = CGRectMake(20, 51, SCREEN_WIDTH - 20 * 2, collectionViewHeight);
        
        [cell.addPictureBtn addTarget:self action:@selector(pickImageFromAlbum) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    } else {
        NSString *ID = @"cellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        }
        if (indexPath.row == 0) {
            NSInteger logoWidth = 80 * displaywidth;
            if (!_userIcon) {
                _userIcon = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH - logoWidth - 15, (90 * displaywidth - logoWidth) / 2, logoWidth, logoWidth) ImageName:@"zhanwei"];
                _userIcon.backgroundColor = [UIColor cyanColor];
                _userIcon.layer.cornerRadius = logoWidth / 2;
                _userIcon.layer.masksToBounds = YES;
                _userIcon.contentMode = UIViewContentModeScaleAspectFill;
                _userIcon.clipsToBounds = YES;
                [_userIcon setContentScaleFactor:[[UIScreen mainScreen] scale]];
                _userIcon.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserIcon)];
                [_userIcon addGestureRecognizer:tap];
            }
            if (![_detailMessageNameArr[0] isEqualToString:@""]) {
                NSURL *url = [NSURL URLWithString:_detailMessageNameArr[0]];
                [_userIcon sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanwei"]];
            }
            [cell.contentView addSubview:_userIcon];
        } else if (indexPath.row == 3 || indexPath.row == 6 || indexPath.row == 8 || indexPath.row == 9){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else if (indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 7) {
            if (![self.view viewWithTag:indexPath.row + 100]) {
                if (indexPath.row == 7) {
                    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 200 * displaywidth - 33, 0, 200 * displaywidth, 45 * displaywidth)];
                    textView.backgroundColor = [UIColor clearColor];
                    textView.delegate = self;
                    textView.tag = indexPath.row + 100;
                    textView.textAlignment = NSTextAlignmentRight;
                    textView.textColor = UIColorHexValue(0xB3B3B3);
                    textView.font = [UIFont systemFontOfSize:14];
                    
                    tipLabel = [ZCControl createLabelWithFrame:CGRectMake(5, 0, textView.frame.size.width-12, 33*displaywidth) Font:14 Text:@"请输入联系地址" Color:UIColorHexValue(0xB3B3B3)];
                    tipLabel.textAlignment = NSTextAlignmentRight;
                    [textView addSubview:tipLabel];
                    [cell.contentView addSubview:textView];
                } else {
                    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 200 * displaywidth - 33, 0, 200 * displaywidth, 45 * displaywidth)];
                    textField.backgroundColor = [UIColor clearColor];
                    textField.delegate = self;
                    textField.tag = indexPath.row + 100;
                    textField.textAlignment = NSTextAlignmentRight;
                    textField.textColor = UIColorHexValue(0xB3B3B3);
                    textField.font = [UIFont systemFontOfSize:14];
                    if (indexPath.row == 1) {
                        textField.placeholder = @"请输入工厂名称";
                    } else if (indexPath.row == 4) {
                        textField.placeholder = @"请输入负责人";
                    } else if (indexPath.row == 5) {
                        textField.placeholder = @"请输入联系电话";
                        textField.keyboardType = UIKeyboardTypePhonePad;
                    }
                    
                    [cell.contentView addSubview:textField];
                }
            }
            UITextField *textField = [self.view viewWithTag:indexPath.row + 100];
            textField.text = _detailMessageNameArr[indexPath.row];
            UITextView *textView = [self.view viewWithTag:indexPath.row + 100];
            textView.text = _detailMessageNameArr[indexPath.row];
        }
        if (indexPath.row != 0 && indexPath.row != 1 && indexPath.row != 4 && indexPath.row != 5 && indexPath.row != 7) {
            cell.detailTextLabel.text = _detailMessageNameArr[indexPath.row];
            cell.detailTextLabel.textColor = UIColorHexValue(0xB3B3B3);
            if (indexPath.row==6) {
                if (longitude>0||latitude>0) {
                    cell.detailTextLabel.text = @"已定位";
                }
            }
        }
        if (indexPath.row == 2) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@", _detailMessageNameArr[2], @"    "];
            cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
        }
        cell.textLabel.text = _messageNameArr[indexPath.row];
        cell.textLabel.textColor = UIColorHexValue(0x4D4D4D);
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
        if (indexPath.row != 3 || indexPath.row != 7 || indexPath.row != 8 || indexPath.row != 6) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF;
    if (indexPath.row == 3) {
        CloseAreaViewController *closeAreaVC = [[CloseAreaViewController alloc] init];
        closeAreaVC.chooseOnlyblock = ^(NSString *modelID, NSString *addressStr) {
            weakSelf.detailMessageNameArr[3] = addressStr;
            weakSelf.areaId = modelID;
            [weakSelf.factoryMessageTableView reloadData];
        };
        [self.navigationController pushViewController:closeAreaVC animated:YES];
    } else if (indexPath.row == 6) {
        FactoryMapViewController *mapVC = [[FactoryMapViewController alloc] init];
        WEAKSELF;
        mapVC.mapBlock = ^(CLLocationCoordinate2D coordinate, NSString *addressStr) {
            weakSelf.coordinate = coordinate;
            longitude = coordinate.longitude;
            latitude = coordinate.latitude;
            _detailMessageNameArr[6] = addressStr;
            _detailMessageNameArr[7] = addressStr;
            tipLabel.hidden = addressStr.length>0?YES:NO;
            [weakSelf.factoryMessageTableView reloadData];
        };
        mapVC.textFieldStr = _detailMessageNameArr[6];
        [self.navigationController pushViewController:mapVC animated:YES];
    } else if (indexPath.row == 8) {
        FactoryIntroductionViewController *factoryIntroVC = [[FactoryIntroductionViewController alloc] init];
        factoryIntroVC.delegate = self;
        factoryIntroVC.introductionStr = _detailMessageNameArr[8];
        [self.navigationController pushViewController:factoryIntroVC animated:YES];
    } else if (indexPath.row == 9) {
        FactoryTypeViewController *factoryTypeVC = [[FactoryTypeViewController alloc] init];
        factoryTypeVC.factoryTypeName = ^(NSString *factoryTypeStr, NSString *productId) {
            weakSelf.detailMessageNameArr[9] = factoryTypeStr;
            weakSelf.productId = productId;
            [weakSelf.factoryMessageTableView reloadData];
        };
        [self.navigationController pushViewController:factoryTypeVC animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

// 将点击tableviewcell的时候收回 searchBar 键盘
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    return indexPath;
}

// MARK:collectionview的方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"collectionViewCellID";
    NSInteger constant = 5;
    NSInteger itemWidth = (SCREEN_WIDTH - 3 * constant * 2 - 40) / 4;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    for (UIView *subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    UIImageView *pictureImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, itemWidth, itemWidth)];
    pictureImageView.backgroundColor = [UIColor cyanColor];
    pictureImageView.contentMode = UIViewContentModeScaleAspectFill;
    pictureImageView.clipsToBounds = YES;
    pictureImageView.userInteractionEnabled = YES;
    pictureImageView.tag = indexPath.row + 1000;
    [pictureImageView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    if (_imageArr.count > 0) {
        pictureImageView.image = _imageArr[indexPath.row];
    }
    UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(itemWidth - 20, 0, 20, 20)];
    deleteBtn.backgroundColor = [UIColor clearColor];
    [deleteBtn addTarget:self action:@selector(onClickDeleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    [deleteBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
    deleteBtn.tag = indexPath.row;
    [pictureImageView addSubview:deleteBtn];
    [cell.contentView addSubview:pictureImageView];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self respondsToSelector:@selector(showImageWithIndexPath:imageIndex:)]) {
        [self showImageWithIndexPath:indexPath.row imageIndex:indexPath.row + 1000];
    }
}

// MARK:请求数据
- (void)saveFactoryMessage {
    UITextField *textField = [self.view viewWithTag:101];
    UITextField *textField1 = [self.view viewWithTag:104];
    UITextField *textField2 = [self.view viewWithTag:105];
    NSString *str = [textField.text isKindOfClass:[NSNull class]] ? @"":textField.text;
    NSString *str1 = [textField1.text isKindOfClass:[NSNull class]] ? @"":textField1.text;
    NSString *str2 = [textField2.text isKindOfClass:[NSNull class]] ? @"":textField2.text;
    if ([_detailMessageNameArr[0] isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请选择公司logo" addToView:self.view];
        return;
    }
    if ([str isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入工厂名称" addToView:self.view];
        return;
    }
    if ([_areaId isEqualToString:@""] || [_areaId isKindOfClass:[NSNull class]] || !_areaId) {
        [LTools showMBProgressWithText:@"请输入常用地" addToView:self.view];
        return;
    }
    if ([str1 isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入负责人" addToView:self.view];
        return;
    }
    if ([str2 isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入联系电话" addToView:self.view];
        return;
    }
//    if ([_detailMessageNameArr[6] isEqualToString:@""]) {
//        [LTools showMBProgressWithText:@"请输入联系地址" addToView:self.view];
//        return;
//    }
    if ([_detailMessageNameArr[7] isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入联系地址" addToView:self.view];
        return;
    }
    if ([_detailMessageNameArr[8] isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入工厂简介" addToView:self.view];
        return;
    }
    if ([_productId isEqualToString:@""] || [_productId isKindOfClass:[NSNull class]] || !_productId) {
        [LTools showMBProgressWithText:@"请输入工厂类型" addToView:self.view];
        return;
    }
    if (_imageArr.count == 0 || !_imageArr || [_imageArr isKindOfClass:[NSNull class]]) {
        [LTools showMBProgressWithText:@"请选择工厂照片" addToView:self.view];
        return;
    }
    
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [HttpTool uploadImageWithPath:SERVER_PictureUpload params:nil thumbName:@"file" ImageAry:_imageArr success:^(id json)
     {
         if ([json server_Getcodecheck])
         {
             _imageStringArr = [NSMutableArray arrayWithArray:json[@"data"]];
             NSMutableArray *imageDicArr = [NSMutableArray array];
             for (int i = 0; i < _imageStringArr.count; i++) {
                 NSDictionary *dic = @{@"url" : _imageStringArr[i]};
                 [imageDicArr addObject:dic];
             }
             NSDictionary *userDic = @{@"name" : str, @"headImg" : _detailMessageNameArr[0], @"area" : @{@"id" : _areaId}, @"lng" : [NSString stringWithFormat:@"%lf", _coordinate.longitude ], @"lat" : [NSString stringWithFormat:@"%lf", _coordinate.latitude]};
             NSDictionary *dic = @{@"phone" : str2, @"user" : userDic, @"linkman" : str1, @"address" : _detailMessageNameArr[7], @"intro" : _detailMessageNameArr[8], @"product" : @{@"id" : _productId}, @"factoryImgs" : imageDicArr};
             
             [HYBaseHandler requestFactoryMessageSaveParmers:dic Success:^(id obj)
              {
                  [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
                  if ([obj server_Getcodecheck])
                  {
                      [LTools showMBProgressWithText:@"保存成功" addToView:weakSelf.view];
                      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                          [self.navigationController popViewControllerAnimated:YES];
                      });
                  }
                  else
                  {
                      [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
                  }
              } failed:^(NSError *error) {
                  [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
                  
              }];
         }
         
     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [LTools showMBProgressWithText:@"上传失败,请重试" addToView:self.view];
     } progress:^(CGFloat progress) {
         
     }];
}

- (void)requestFactoryMessage {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestFactoryInfoParmers:nil Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *dataArr = [FactoryMessageModel mj_objectArrayWithKeyValuesArray:@[obj[@"data"]]];
             NSMutableArray *tempImageArr = [NSMutableArray array];
             FactoryMessageModel *messageModel = dataArr[0];
             for (int i = 0; i < messageModel.factoryImgs.count; i++) {
                 FactoryImgsModel *imgsModel = messageModel.factoryImgs[i];
                 UIImage *image = [UIImage imageWithData:[NSData  dataWithContentsOfURL:[NSURL URLWithString:imgsModel.url]]];
                 [tempImageArr addObject:image];
             }
             FactoryProductModel *productModel = messageModel.product;
             FactoryCategoryModel *catetoryModel = productModel.category;
             UserModel *userModel = messageModel.user;
             
             NSString *str = [userModel.province isKindOfClass:[NSNull class]] || !userModel.province ? @"" : userModel.province;
             NSString *str1 = [userModel.city isKindOfClass:[NSNull class]] || !userModel.city ? @"" : userModel.city;
             NSString *str2 = [userModel.province isKindOfClass:[NSNull class]] || !userModel.areaName ? @"" : userModel.areaName;
             NSString *str3 = [catetoryModel.name isKindOfClass:[NSNull class]] || !catetoryModel.name ? @"" : catetoryModel.name;
             NSString *str4 = [productModel.name isKindOfClass:[NSNull class]] || !productModel.name ? @"" : productModel.name;
             _detailMessageNameArr[0] = userModel.headImg;
             _detailMessageNameArr[1] = userModel.name;
             _detailMessageNameArr[2] = userModel.mark;
             _detailMessageNameArr[3] = [NSString stringWithFormat:@"%@%@%@", str, str1, str2];
             _detailMessageNameArr[4] = messageModel.linkman;
             _detailMessageNameArr[5] = messageModel.phone;
             _detailMessageNameArr[7] = messageModel.address;
             tipLabel.hidden = messageModel.address.length>0?YES:NO;
             _detailMessageNameArr[8] = messageModel.intro;
             _detailMessageNameArr[9] = [NSString stringWithFormat:@"%@/%@", str3, str4];
             _areaId = userModel.areaId;
             _productId = productModel.category.ID;
             longitude = [userModel.lng doubleValue];
             latitude = [userModel.lat doubleValue];
             _imageArr = [NSMutableArray arrayWithArray:tempImageArr];
             [_factoryMessageTableView reloadData];
             [_pictureCollectionView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

// MARK: - KSPhotoBrowserDelegate

- (void)ks_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index {
    NSLog(@"selected index: %ld", index);
}

- (void)showImageWithIndexPath:(NSInteger)index imageIndex:(NSInteger)imageIndex
{
    [photoArr removeAllObjects];
    for (int i = 0; i < _imageArr.count; i++) {
        UICollectionViewCell *cell = (UICollectionViewCell *)[_pictureCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        UIImageView *imageView = [cell.contentView viewWithTag:i];
        KSPhotoItem *item = [KSPhotoItem itemWithSourceView:imageView image:_imageArr[i]];
        [photoArr addObject:item];
    }
    KSPhotoBrowser *ksBrowser = [KSPhotoBrowser browserWithPhotoItems:photoArr selectedIndex:index];
    [KSPhotoBrowser setImageManagerClass:KSYYImageManager.class];
    ksBrowser.delegate = self;
    ksBrowser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
    ksBrowser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlurPhoto;
    ksBrowser.loadingStyle = KSPhotoBrowserImageLoadingStyleIndeterminate;
    ksBrowser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleText;
    ksBrowser.bounces = NO;
    [ksBrowser showFromViewController:self];
}

// MARK:TZImagePickerController
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    [self.imageArr addObjectsFromArray:photos];
    
    [_factoryMessageTableView reloadData];
    [_pictureCollectionView reloadData];
}

//需求：相册里的视频隐藏不给选。(不知道后面会不会又要选视频先留着)
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset
{
    
}

// MARK:处理键盘遮住和退出键盘
// 我们获取当前tableView 的偏移量
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    /* scrollView 的偏移量*/
//    CGFloat offSetY = scrollView.contentOffset.y;
//    scrollViewOffSetY = offSetY;

}
// 我们获取那个Cell是被点击的
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    /* 获取当前cell的位置*/
    /* 我们进行层次分析
     * A.superview 则是 cell
     */
    scrollViewOffSetY = _factoryMessageTableView.contentOffset.y;
    CGFloat Hieght = textField.superview.superview.frame.origin.y;
    /* 获取当前点击Cell的位置*/
    CGFloat CurrentCellY = Hieght - scrollViewOffSetY;
    /* 获取剩余高度*/
    CGFloat lastHeight = [UIScreen mainScreen].bounds.size.height - CurrentCellY-200;
    remainingDistanceY = lastHeight;
    
    
}
// 我们在获取弹出键盘的高度和在做计算差值偏移
-(void)jianpantanchu:(NSNotification*)Notification{
    NSLog(@"%@",Notification);
    /* 获取键盘的开始高度*/
    NSDictionary *userInfo = [Notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat keyBoardStart = keyboardRect.size.height;
    
    //    CGFloat keyBoardStart = [Notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue].size.height;
    if (remainingDistanceY < keyBoardStart) {
        /* 获取差值*/
        CGFloat differenceValue = keyBoardStart -remainingDistanceY;
        beforeMigrationY = differenceValue;
        [_factoryMessageTableView setContentOffset:CGPointMake(0, differenceValue + scrollViewOffSetY) animated:YES];
    }
}

// 我们为了防止tableView不能返回原始没有被点击的位置(这是防止用户在键盘弹出的时候，在滑动而造成的混乱)
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.view endEditing:YES];
}
// 最后键盘隐藏，返回点击前的偏移
-(void)jianpanhuishou:(NSNotification*)Notification{
    NSLog(@"Hide");
    [_factoryMessageTableView setContentOffset:CGPointMake(0, scrollViewOffSetY) animated:YES];
    beforeMigrationY = 0.0;
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.isEditing) {
        [textField endEditing:YES];
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        tipLabel.hidden = YES;
    } else {
        tipLabel.hidden = NO;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    _detailMessageNameArr[textField.tag - 100] = textField.text;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    _detailMessageNameArr[textView.tag - 100] = textView.text;
}
// MARK:工厂介绍代理
-(void)getFactoryIntroduction:(NSString *)factoryIntro {
    _detailMessageNameArr[8] = factoryIntro;
    [_factoryMessageTableView reloadData];
}
// MARK:点击事件
- (void)onClickDeleteBtn:(UIButton *)sender {
    [self.imageArr removeObjectAtIndex:sender.tag];
    [_pictureCollectionView reloadData];
    [_factoryMessageTableView reloadData];
}

- (void)changeUserIcon {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [self takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [self dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)pickImageFromAlbum {
    TZImagePickerController *moreChoseImagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:8 delegate:self];
    moreChoseImagePicker.maxImagesCount = 8 - _imageArr.count;
    moreChoseImagePicker.allowPickingVideo = NO;
    moreChoseImagePicker.allowTakePicture = NO;
    [self presentViewController:moreChoseImagePicker animated:YES completion:nil];
}

// MARK:系统自带相册
-(void)takePhoto
{
    //判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
    }
    _userIcon.image = image;
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HttpTool uploadImageWithPath:SERVER_PictureUpload params:nil thumbName:@"file" image:image success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([json server_Getcodecheck])
         {
             NSArray *dataArr = json[@"data"];
             _detailMessageNameArr[0] = dataArr[0];
         }

     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [LTools showMBProgressWithText:@"上传失败,请重试" addToView:self.view];
     } progress:^(CGFloat progress) {

     }];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
